
$(function () {
    var streamAddEvent,
        streamEndEvent,
        agentJoinSessionEvent,
        agentQuitSessionEvent,
        customerJoinSessionEvent,
        customerQuitSessionEvent;
    var isRobotAgent = false;
    var roomInfo;
    var publicationId;
    var callMediaType = 'video';
    var receiveMediaType = 'video';
    var participantId = '';
    var robotClientId = '';
    var getStatsIntervalId = 0;

    $('#webrtc').on('click', () => {
        console.log('is support', ivcs.client.isSupportWebrtc());
    });

    $('#screenshot').on('click', function () {
        console.log(ivcs.client);
        ivcs.client.snapshot(
            document.body,
            {
                width: window.screen.availWidth, // TODO 截屏按照1920*1080分辨率下的预览窗口宽高
                height: window.screen.availHeight,
                x: 0,
                y: 0,
            },
            true,
            {},
            (resp) => {
                console.log('snapshot success', resp);
                document.body.appendChild(resp.imgCanvas);
            },
            (error) => {
                console.log('snapshot error', error);
            }
        );
    });

    $('#mic').on('click', function () {
        ivcs.client.microphoneTest(
            (resp) => {
                console.log('success', resp);
            },
            (error) => {
                console.log('error', error);
            }
        );
    });

    $('#camera').on('click', function () {
        ivcs.client.cameraTest(
            null,
            (resp) => {
                console.log('success', resp);
            },
            (error) => {
                console.log('error', error);
            }
        );
    });

    $('#start_nerwork').on('click', function () {
        let online = ivcs.client.startMonitorNetwork((status) => {
            console.log('now network status', status);
        });
        alert('网络' + online);
    });
    $('#stop_nerwork').on('click', function () {
        ivcs.client.stopMonitorNetwork();
    });

    // 免密初始化
    $('#nopassword_connect_btn').on('click', function () {
        let backendUrl = "https://192.168.31.187";
        let testOrg = document.getElementById('org').value;
        let userId = document.getElementById('userId').value;
        ivcs.client.initWithoutPassword(backendUrl,userId,testOrg,undefined,(s)=>{
            console.log('s',s);
        },(e)=>{
            console.log('e',e);
        }, {
            isOpen: false,
        });
    });

    $('#visitor_connect_btn').on('click', function () {
        let backendUrl = document.getElementById('backend_url_id').value;
        let accessToken =
            'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7ImlkIjo1MCwidXNlck5hbWUiOiIwMDEiLCJvcmciOiIxIiwicm9sZSI6ImN1c3RvbWVyIiwiaXNEaXNhYmxlZCI6Ik4iLCJpc1JvYm90IjpmYWxzZSwicHJvZmlsZSI6eyJnZW5kZXIiOiLlpbMiLCJwaWN0dXJlIjoiaHR0cDovL3plYWxjb21tLWZpbGV1cGxvYWQub3NzLWNuLXNoYW5naGFpLmFsaXl1bmNzLmNvbS8yZjY1ZmY3YWFlMjYwYjk1YjY5NzYyMDBkNThiNzNiNiIsImZ1bGxOYW1lIjoi5a2Z6LCi6LCiIn0sImN1c3RvbWVyTGV2ZWwiOjEsIl9pZCI6NTAsInNjaGVkdWxpbmdBdHRyaWJ1dGVzIjp7fX0sImlhdCI6MTYyNzcxMzgxOCwiZXhwIjoxNjI3NzU3MDE4fQ.f_rb5hBPz_kHrH8iQUSkXy5zPsQn15cA9qpAt2odrAg';
        let tokenData = {
            data: {
                id: 50,
                userName: '001',
                org: '1',
                role: 'customer',
                isDisabled: 'N',
                isRobot: false,
                profile: { isRobot: false },
                customerLevel: null,
                _id: 50,
                schedulingAttributes: {
                    是否机器人: 'false',
                },
            },
            exp: 1627757018,
            iat: 1627713818,
        };
        let associatedUrls = {
            backendurl: 'https://ivcs-xxx.xxx.xx',
            ccsurl: 'https://ivcs-xxx.xxx.xx',
            domainType: 'public',
            icbcAxaBackendUrl: 'https://localhost:3095',
            turnserverCredential: 'test',
            turnserverUrl: 'turn:localhost?transport=tcp',
            turnserverUsername: 'test',
            uploadUrl: 'https://ivcs-xxx.xxx.xx',
        };
        let ticket =
            'RWqmtFeTqB7LDq7IuY6McZK44KoWLVzSeYUyJRcF9eQz3F_9b-zSWroDJr2Og2fs';
        console.log(parseInt(tokenData.exp) - parseInt(tokenData.iat) - 1);
        let mediaOptions = undefined;
        ivcs.client.unRegisteredInit(
            backendUrl,
            'openId123',
            undefined,
            (resp) => {
                console.log('unRegisteredInit success', resp);
                $('#connect_btn').attr('disabled', true);
                $('#visitor_connect_btn').attr('disabled', true);
                // $("#reqsess_btn_video_video").attr('disabled',false);
                // $("#reqsess_btn_video_video").attr('disabled',false);
                // $("#reqsess_btn_video_video").attr('disabled',false);
                // $("#reqsess_btn_video_video").attr('disabled',false);
                callBtnDisable(false);
            },
            (error) => {
                console.log('unRegisteredInit failed', error);
            },
            {
                isOpen: false,
            }
        );
        ivcs.client.addEventListener('systemError', (error) => {
            console.log('system error', error);
            $('#connect_btn').attr('disabled', false);
            $('#visitor_connect_btn').attr('disabled', false);
            callBtnDisable(false);
        });
    });

    //呼叫按钮是否可用
    function callBtnDisable(flag) {
        $('#reqsess_btn_video_video').attr('disabled', flag);
        $('#reqsess_btn_video_audio').attr('disabled', flag);
        $('#reqsess_btn_audio_video').attr('disabled', flag);
        $('#reqsess_btn_audio_audio').attr('disabled', flag);
    }
    /**
     * CCS服务建立socket连接
     */
    $('#connect_btn').on('click', function () {
        console.log(ivcs);
        let testName = document.getElementById('name').value;
        let testPwd = document.getElementById('pwd').value;
        let testOrg = document.getElementById('org').value;
        let backendUrl = document.getElementById('backend_url_id').value;
        ivcs.client.init(
            backendUrl,
            testName,
            testPwd,
            testOrg,
            undefined,
            (resp) => {
                console.log('init ccs success', resp);
                $('#connect_btn').attr('disabled', true);
                $('#visitor_connect_btn').attr('disabled', true);
                callBtnDisable(false);
            },
            (error) => {
                console.log('init ccs failed', error);
            }
        );
        ivcs.client.addEventListener('systemError', (error) => {
            console.log('system error', error);
            $('#connect_btn').attr('disabled', false);
            $('#visitor_connect_btn').attr('disabled', false);
            callBtnDisable(false);
        });
    });

    /**
     * 访客请求通话
     * @param {*} callMediaType  访客端的媒体类型 audio/video
     * @param {*} receiveMediaType 坐席端的媒体类型 audio/video
     */
    function requestSession(callMediaType, receiveMediaType, isAgentZ = false) {
        let skill = $('#group').val();
        let userData = {
            media: callMediaType,
            userData: {
                service: skill,
                specifyAgent: '',
                testId: '123',
                callMediaType: callMediaType,
                receiveMedia: receiveMediaType,
                virtualAgentType: isAgentZ ? 'unregistered' : 'registered', //虚拟坐席的类型，agentZ是未注册的坐席
            },
            clientInfo: {},
        };
        console.log('request data', userData);

        ivcs.client.requestSession(
            userData,
            function (resp) {
                console.log('request success,', resp);
                callMediaType = callMediaType;
                receiveMediaType = receiveMediaType;

                callBtnDisable(true);
                $('#quitsession_btn').attr('disabled', false);
                $('#shareresource').attr('disabled', false);
                $('#audio-video').attr('disabled', false);
                $('#mute').attr('disabled', false);
                $('#sessionId').html('sessionId=' + resp.sessionId);

                ivcs.client.onInvitationProgress((resp) => {
                    console.log('invite progress', resp);
                    console.log(resp.message);
                });
                sessionParticipantEvent();
                sessionStreamEvent();
                textMessageEvent();
                ivcs.client.onReadyToTalk((resp) => {
                    console.log('agent video ready', resp);
                    if (!isRobotAgent) {
                        ivcs.client.startVideo(
                            'customer',
                            callMediaType,
                            (resp) => {
                                console.log('start video success', resp);
                                //接收自定义消息
                                ivcs.client.onCustomMessage((message) => {
                                    console.log(
                                        'receive custom message:',
                                        message
                                    );
                                });
                                participantId = resp.roomInfo.self.id;
                            },
                            (error) => {
                                console.log('start video failed', error);
                            }
                        );
                    }
                });

                ivcs.client.onResourceMessage(function (data) {
                    console.log('receive resource message,,', data);
                    $('#message_list').append(
                        $('<li>').text(`${JSON.stringify(data)}`)
                    );
                    let message = {
                        answer: 'ok',
                        type: 'text',
                        data: '',
                    };
                    sendMessageConfirmationToAgent(message);
                });

                ivcs.client.onHoldOn((data) => {
                    console.log('onhold on message,,', data);
                    $('#message_list').append(
                        $('<li>').text(`${JSON.stringify(data)}`)
                    );
                    let message = {
                        answer: 'ok',
                        type: 'text',
                        data: '',
                    };
                    sendMessageConfirmationToAgent(message);
                });

                // ivcs.client.onScreenSnapshotRequest((data) => {
                //     console.log('onScreenSnapshot', data);
                //     alert('坐席请求截取你的图片');
                //     //这个地方，前端处理截取本地camera图片并上传，然后调用shareResourceWithUrl 发送图片给坐席
                //     let message = {
                //         answer: 'ok',
                //         type: 'text',
                //         data: '',
                //     };
                //     sendMessageConfirmationToAgent(message);
                // });

                // ivcs.client.onPhotoGuideBox((data) => {
                //     console.log('onPhotoGuideBox', data);
                //     alert(
                //         '坐席推送引导框指令给访客，访客端需要自己处理，在视频页面绘制引导框'
                //     );
                //     //web端自己处理，可生成业务需要的引导框的样式图在访客的页面上。
                // });

                // ivcs.client.onHandSignatureRequest((data) => {
                //     console.log('on HandSignature data', data);
                //     if (data.data === 'start') {
                //         console.log('坐席邀请你手写签名');
                //     }
                //     let message = {
                //         answer: 'ok',
                //         type: 'text',
                //         data: '',
                //     };
                //     sendMessageConfirmationToAgent(message);
                // });
            },
            function (error) {
                console.log('error,,', error);
            }
        );
    }

    $('#reqsess_btn_video_video_agentZ').on('click', function () {
        requestSession('video', 'video', true);
    });

    $('#reqsess_btn_video_video').on('click', function () {
        requestSession('video', 'video');
    });

    $('#reqsess_btn_video_audio').on('click', function () {
        requestSession('video', 'audio');
    });

    $('#reqsess_btn_audio_video').on('click', function () {
        requestSession('audio', 'video');
    });

    $('#reqsess_btn_audio_audio').on('click', function () {
        requestSession('audio', 'audio');
    });

    function sendMessageConfirmationToAgent(data) {
        ivcs.client.sendMessageConfirmation(
            data,
            'agents',
            (resp) => {
                console.log('sendMessageConfirmationToAgent succes', resp);
            },
            (error) => {
                console.log('sendMessageConfirmationToAgent error', error);
            }
        );
    }

    function sessionParticipantEvent() {
        customerJoinSessionEvent = ivcs.client.addEventListener(
            'onCustomerJoinSession',
            (info) => {
                console.log('onCustomerJoinSession', info);
            }
        );

        agentQuitSessionEvent = ivcs.client.addEventListener(
            'onAgentQuitSession',
            (info) => {
                console.log('onAgentQuitSession', info);
                alert('坐席离开会话');
            }
        );

        customerQuitSessionEvent = ivcs.client.addEventListener(
            'onCustomerQuitSession',
            (info) => {
                console.log('onCustomerQuitSession', info);
            }
        );

        agentJoinSessionEvent = ivcs.client.addEventListener(
            'onAgentJoinSession',
            async (info) => {
                console.log('onAgentJoinSession', info);
                if (
                    info.data &&
                    info.data.user &&
                    info.data.user.profile &&
                    info.data.user.profile.isRobot
                ) {
                    //机器人客服
                    if (!participantId) {
                        ivcs.client.startVideo(
                            'customer',
                            'video',
                            async (resp) => {
                                console.log('start video success', resp);
                                //接收自定义消息
                                ivcs.client.onCustomMessage((message) => {
                                    console.log(
                                        'receive custom message:',
                                        message
                                    );
                                });
                                //并告知机器人客服视频已准备好
                                let participantId = resp.roomInfo.self.id;
                                roomInfo = resp.roomInfo;
                                publicationId = resp.publicationId;
                                let user = {
                                    picture: '111',
                                    fullName: '张三',
                                    gender: '先生',
                                };
                                isRobotAgent = true;
                                console.log(participantId);
                                console.log(
                                    'tellRobotAgent participantId',
                                    participantId
                                );
                                robotClientId = info.data.id;
                                await noticeRobotCustomerJoinRoom(
                                    user,
                                    robotClientId
                                );
                            },
                            (error) => {
                                console.log('start video failed', error);
                            }
                        );
                    } else {
                        let user = {
                            picture: '111',
                            fullName: '张三',
                            gender: '先生',
                        };
                        isRobotAgent = true;
                        console.log(participantId);
                        console.log(
                            'tellRobotAgent participantId',
                            participantId
                        );
                        robotClientId = info.data.id;
                        await noticeRobotCustomerJoinRoom(user, robotClientId);
                    }
                }
            }
        );
    }

    function sessionStreamEvent() {
        streamAddEvent = ivcs.client.addEventListener(
            'onStreamAdd',
            (streamInfo) => {
                console.log('demo stream add', streamInfo);
                var label = streamInfo.data.streamLabel;
                if (label == 'recordScreen') {
                    console.log('is record screen stream');
                    return;
                }
                if (label !== '' && label !== 'screen' && label != 'customer') {
                    //坐席流
                    addVideoView(label);
                    ivcs.client.renderStream(
                        label,
                        label,
                        async (resp) => {
                            console.log('render success', resp, label, label);
                            await readyToTalkRobotAgent(
                                participantId,
                                {},
                                robotClientId
                            );
                            //获取订阅流的网络监控数据
                            getRemoteStreamStats(label);
                        },
                        (error) => {
                            console.log('render error', error);
                        },
                        (playError) => {
                            console.log('render stream playError', playError);
                        },
                        (onended) => {
                            console.log('render stream end', onended);
                        }
                    );
                }
                if (label === 'customer') {
                    //访客
                    addVideoView(label);
                    ivcs.client.renderStream(
                        label,
                        label,
                        async (resp) => {
                            console.log('render success', resp, label, label);
                        },
                        (error) => {
                            console.log('render error', error);
                        },
                        (playError) => {
                            console.log('render stream playError', playError);
                        },
                        (onended) => {
                            console.log('render stream end', onended);
                        }
                    );
                }
            }
        );
        streamEndEvent = ivcs.client.addEventListener(
            'onStreamEnd',
            function (streamInfo) {
                console.log('onStreamEnd', streamInfo);
            }
        );
    }

    function getRemoteStreamStats(streamlabel){
        ivcs.client.getRemoteStreamStats(streamlabel,2000,(s)=>{
            console.log('getRemoteStreamStats data',s);
        },(e)=>{
            console.log('getRemoteStreamStats error',e);
        })
    }

    function textMessageEvent() {
        ivcs.client.onTextMessage((resp) => {
            console.log('on text message', resp);
            $('#message_list').append(
                $('<li>').text(`${JSON.stringify(resp)}`)
            );
        });
    }

    /**
     * 语音升级成视频通话
     */
    $('#audio-video').on('click', function () {
        ivcs.client.voiceToVideo(
            (resp) => {
                console.log('voice to video success', resp);
            },
            (error) => {
                console.log('voice to video error', error);
            }
        );
    });
    /**
     *  发送消息
     */
    $('#sed_btn').on('click', function () {
        let msg = $('#msg_id').val();
        if (!msg) {
            console.log('place input msg!');
            return;
        }
        ivcs.client.sendTextMessage(
            msg,
            undefined,
            (resp) => {
                console.log('send success', resp);
                $('#message_list').append($('<li>').text(`${msg}`));
            },
            (error) => {
                console.log('send error', error);
            }
        );

        //发送自定义消息
        ivcs.client.sendCustomMessage(
            'custom test message from customer' + msg,
            undefined,
            (resp) => {
                console.log('send custom success', resp);
            },
            (error) => {
                console.log(error);
            }
        );
    });

    /**
     * 取消/退出会话
     */
    $('#quitsession_btn').on('click', function () {
        ivcs.client.quitSession(
            {
                reason: '客户挂断',
            },
            function (resp) {
                console.log('quit session', resp);
                callBtnDisable(true);
                $('#quitsession_btn').attr('disabled', true);
                $('#connect_btn').attr('disabled', false);
                $('#visitor_connect_btn').attr('disabled', false);
                $('ul li').remove();
            },
            function (error) {
                console.log('error,', error);
            }
        );
        isRobotAgent = false;
        participantId = null;
        // ivcs.client.removeEventListener('onStreamAdd', streamAddEvent);
        ivcs.client.removeEventListener('onStreamEnd', streamEndEvent);
        ivcs.client.removeEventListener(
            'onCustomerJoinSession',
            customerJoinSessionEvent
        );
        ivcs.client.removeEventListener(
            'onAgentQuitSession',
            agentQuitSessionEvent
        );
        ivcs.client.removeEventListener(
            'onCustomerQuitSession',
            customerQuitSessionEvent
        );
        ivcs.client.removeEventListener(
            'onAgentJoinSession',
            agentJoinSessionEvent
        );
        removeAllVideoView();
    });

    $('#shareresource').on('click', function () {
        var file = document.getElementById('input').files[0];
        var formData = new FormData();
        formData.append('file', file);
        ivcs.client.shareResource(
            'doc',
            formData,
            undefined,
            function (resp) {
                console.log('share resource success', resp);
                $('#message_list').append(
                    $('<li>').text(`${JSON.stringify(resp)}`)
                );
            },
            function (error) {
                console.log('share resource failed', error);
            }
        );
    });

    $('#mute').on('click', function () {
        ivcs.client.mute(
            'audio',
            function () {
                console.log('mute audio succss');
                $('#unmute').attr('disabled', false);
                $('#mute').attr('disabled', true);
            },
            function (error) {
                console.log('mute audio failed', error);
            }
        );
    });

    $('#unmute').on('click', function () {
        ivcs.client.unmute(
            'audio',
            function () {
                console.log('unmute audio succss');
                $('#mute').attr('disabled', false);
                $('#unmute').attr('disabled', true);
            },
            function (error) {
                console.log('unmute audio failed', error);
            }
        );
    });

    $('#send_handSign').on('click', function () {
        //模拟发送签名数据，，具体可结合前端的笔迹框架实现
        ivcs.client.sendHandSignMessage(
            'test hand sign data',
            undefined,
            (resp) => {
                console.log('send hand sign message,success', resp);
            },
            (error) => {
                console.log('send hand sign message,failed', error);
            }
        );
    });

    //获取网络数据
    $('#getstats').on('click', function () {
        getStatsIntervalId = ivcs.client.getLocalStreamStats(
            3000,
            (resp) => {
                console.log(
                    'get getLocalStreamStats,success',
                    resp,
                    new Date()
                );
            },
            (error) => {
                console.log('get getLocalStreamStats,failed', error);
            }
        );
    });

    //停止获取自己推流的网络数据
    $('#stopgetstats').on('click', function () {
        ivcs.client.stopLocalStreamStats(
            getStatsIntervalId,
            (resp) => {
                console.log('stopLocalStreamStats,success', resp, new Date());
            },
            (error) => {
                console.log('stopLocalStreamStats,failed', error);
            }
        );
    });

    //主动邀请人工坐席
    $('#invite_agent').on('click', function () {
        let bizScenarioId = $('#invite_bizscenarioId').val();
        let agentId = $('#invite_agentId').val();
        console.log(bizScenarioId, agentId);
        let option = {
            agentId: agentId,
            service: bizScenarioId,
            bizSceneName: '',
            userData: {},
            filter: [
                {
                    attribute: '是否机器人',
                    rule: 'ne', //不等于
                    value: 'true',
                },
            ],
        };
        console.log('invite-agent parameter', option);
        ivcs.client.inviteOther(
            option,
            (s) => {
                console.log('inviteOther success', s);
            },
            (e) => {
                console.log('inviteOther error', e);
            }
        );
    });

    //主动邀请AI坐席
    $('#invite_robot_agent').on('click', function () {
        let bizScenarioId = $('#invite_bizscenarioId').val();
        let agentId = $('#invite_robot_agentId').val();
        console.log(bizScenarioId, agentId);
        console.log(bizScenarioId, agentId);
        let option = {
            agentId: agentId,
            service: bizScenarioId,
            bizSceneName: '',
            userData: {},
            filter: [
                {
                    attribute: '是否机器人',
                    rule: 'ne', //不等于
                    value: 'false',
                },
            ],
        };
        console.log('invite-agent parameter', option);
        ivcs.client.inviteOther(
            option,
            (s) => {
                console.log('inviteOther success', s);
            },
            (e) => {
                console.log('inviteOther error', e);
            }
        );
    });

    /**
     * 通知坐席，访客已经加入房间，可以加载机器人资源
     */
    async function noticeRobotCustomerJoinRoom(user, agentClientId) {
        let self = this;
        return await new Promise((resolve, reject) => {
            // eslint-disable-next-line no-undef
            console.log(user, agentClientId);
            ivcs.client.noticeCustomerJoinRoom(
                user,
                agentClientId,
                (s) => {
                    console.log('noticeRobotCustomerJoinRoom success', s);
                    resolve(s);
                },
                (error) => {
                    console.log('noticeRobotCustomerJoinRoom failed', error);
                    reject(error);
                }
            );
        });
    }

    /**
     * 告知坐席，访客已经订阅好机器人,机器人可以播报话术
     */
    async function readyToTalkRobotAgent(participantId, user, agentClientId) {
        return await new Promise((resolve, reject) => {
            // eslint-disable-next-line no-undef
            ivcs.client.readyToTalk(
                participantId,
                user,
                agentClientId,
                (s) => {
                    console.log('tell agent ready to talk success', s);
                    resolve(s);
                },
                (error) => {
                    console.log('tell agent ready to talk failed', error);
                    reject(error);
                }
            );
        });
    }

    function addVideoView(id) {
        var videoView = document.createElement('VIDEO');
        videoView.setAttribute('width', '320');
        videoView.setAttribute('height', '240');
        videoView.setAttribute('controls', 'controls');
        videoView.setAttribute('muted', 'muted');
        videoView.setAttribute('id', id);
        videoView.setAttribute('autoplay', 'autoplay');
        document.body.appendChild(videoView);
    }

    function removeAllVideoView() {
        var tagElements = document.getElementsByTagName('VIDEO');
        let length = tagElements.length;
        for (let m = 0; m < length; m++) {
            console.log(tagElements);
            tagElements[0].parentNode.removeChild(tagElements[0]);
        }
    }
});
